<template>
    <div class="login-box">
        <!-- 在用户进入界面的时候，不应该立即展示用户的登录界面，展示广告、系统欢迎界面 -->
        <div v-if="welcome" class="welcome">
            <!-- 在组件的click上有一个方法可以触发原生事件，添加修饰符 -->
            <van-circle v-model="currentTime"
                style="position: absolute; top: 10px; right: 10px;"
                size="56px"
                :rate="currentTime"
                v-on:click.native="closeWelcome"
                :text="`${time}s`"/>
            <i class="icon"></i>
            <span>{{welText}}</span>
        </div>
        <div v-else class="login">
                <div class="nav">
                   <span class="log">登录</span>
                    <span @click="goRegister">注册</span>
                </div>
                <div class="ipt-box">
                    <img src="../../images/user.png"><input v-model="loginObj.phone" type="text" placeholder="输入手机号">
                </div>
                <div class="ipt-box">
                    <img src="../../images/pwd.png"><input v-model="loginObj.cdtCode" type="text" placeholder="输入验证码">
                    <!-- 获取验证码的标识就是文字 -->
                    <van-button @click="getVdtCode" class="btn" >{{vdtText}}</van-button>
                </div>
                <van-checkbox v-model="remember" checked-color="#FBD216">记住手机号？</van-checkbox>

                <van-checkbox v-model="auto" checked-color="#FBD216">7天免登录？</van-checkbox>
                
                <van-button @click="loginEvt"
                    color="linear-gradient(to right, #FBD216, #ee0a24)"
                    :loading="loading"
                    loading-text="登录中..."
                    :disabled="!/^1[3-9]{1}[0-9]{9}$/.test(loginObj.phone) || loginObj.cdtCode.length !== 4"
                    round block>登录</van-button>
        </div>
    </div>
</template>

<script>
    import { autoLoginApi, getUserInfoApi, getVdtCodeApi, loginApi } from '../../apis/loginApi'

    export default {
        data(){
            return {
                welcome:true,
                welText:'每个人都是美食家',
                //记住手机号
                remember:false,
                auto:false,
                 //7天内免登录标识
                autoFlag:'login',
                //登陆的节流标识
                loading:false,
                loginObj:{
                    phone:'',
                    cdtCode:''
                },
                vdtText:'获取验证码',
                timer:null,
                time:5,
                currentTime: 100,
            }
        },
        async created (){
            this.timer = setInterval(() => {
                if (this.currentTime > 0) {
                    this.currentTime -= 1
                    this.time = Math.ceil(this.currentTime / 20)
                    // console.log('------------', this.currentTime)
                } else {
                    // 倒计时到了，要判断免登录结果，如果错误就需要把欢迎页面关闭，如果success则跳转到首页
                    // 关闭倒计时
                    clearInterval(this.timer)
                    this.timer = null // 释放变量
                    
                    if (this.autoFlag === 'success') {
                        this.$router.push('/home')
                    } else {
                        this.welcome = false
                    }
                }
            }, 50)
            let autoLogin = localStorage.getItem('auto-login')

            if (!!autoLogin) {
                this.$store.commit('common/setToken', autoLogin)

                let result = await autoLoginApi()

                if (result.code === 200) {
                    this.autoFlag = 'success'
                    // 缓存用户信息
                    this.$store.commit('common/setUserInfo',result.data)
                } else {
                    this.autoFlag = 'error'
                }
            } else {
                // 读取手机号缓存
                let userPhone = localStorage.getItem('user-phone')
                if (!!userPhone) {
                    this.loginObj.phone = userPhone
                    this.remember = true
                }

                //免登录失败
                this.autoFlag = 'error'
            }
        },
        methods:{
            closeWelcome() {
                console.log('-------------------------------')
                // 免登录进行中 -- 不执行任何业务
                if (this.autoFlag === 'login') return

                // 只要免登录完成以后都需要关闭定时器
                clearInterval(this.timer)

                // 登录成功
                if (this.autoFlag === 'success') {
                    this.$router.push('/home')
                } else {
                    this.welcome = false
                }
            },
            goRegister(){
                this.$router.push('/register')
            },
            
           
            async loginEvt(){
                //开启节流
                this.loading = true
                let result = await loginApi ( this.loginObj.phone,this.loginObj.cdtCode)
                // console.log('this.loginObj---',this.loginObj);
                // debugger;
                console.log('res:------',result);
                if (result.code !== 200 ) {
                    this.$toast.fail ('登录失败,请重试')
                    //重置节流
                    this.loading = false
                    return 
                }
                

                this.$store.commit('common/setToken',result.data.token)

                let user =  await getUserInfoApi(result.data.id)

                //缓存用户信息
                this.$store.commit('common/setUserInfo',result.data)

                //判断是否同意免登录
                if (this.auto){
                    localStorage.setItem('auto-login',result.data.token)
                } else {
                    localStorage.removeItem('auto-login')
                }

                //记住手机号
                if (this.remember) {
                    localStorage.setItem('user-phone',this.loginObj.phone)
                } else {
                    localStorage.removeItem('user-phone')
                }

                this.$router.push('/home')
            },

            async getVdtCode () {
                if (this.vdtText !== '获取验证码') return

                if (!/^1[3-9]{1}[0-9]{9}$/.test(this.loginObj.phone)) {
                    this.$toast({
                        message:'请输入正确的手机号',
                        position:'bottom'
                    })
                    return
                }

                this.vdtText = '正在获取'

                let result = await getVdtCodeApi (this.loginObj.phone)

                if (result.code !== 200) {
                    this.$toast.fail('获取验证码失败，请重试')
                    this.vdtText = '获取验证码'
                    return 
                }

                this.$toast.success(`获取验证码成功,验证码为:${result.data.code}`)
            },

             // 递归实现倒计时
            loopTimer(_st) {
                // 获取当前时间，然后减去开始时间得到过去的时间
                let _pt = Math.ceil((Date.now() - _st) / 1000)
                this.vdtText = `重新获取(${5 - _pt}s)`
                setTimeout(() => {
                    // 实现递归
                    // 判断已经过去的时间要小于等待时间
                    if (_pt < 5) {
                        this.loopTimer(_st)
                    } else {
                        this.vdtText = '获取验证码'
                    }
                }, 100)
            },
        }
    }
</script>

<style lang="less" scoped>
    @import "../../style/common.less";
    .login-box {
        display: block;
        position: relative;
        height: 100%;
        padding: 4vh 20px 0;

        .welcome {
            .icon {
                display: block;
                margin: 16vh auto 0;
                width: 180px;
                height: 180px;
                background: url(../../images/login_pic.png) center center / 100% 100% no-repeat;
            }
            > span {
                display: block;
                padding: 30px 0;
                font-size: .8rem;
                color: @primary;
                text-align: center;
            }
        }
        .nav {
            display: flex;
            > span {
                margin: 30px 30px;
                line-height: 30px;
            }
            .log {
                font-size: 30px;
                color: @primary;
            }
        }
    
        .login {
            > .ipt-box {
                display: flex;
                padding: 10px 0;
                margin-bottom: 16px;
                border-bottom: solid 1px @cdd;
                input {
                    flex: 1;
                    height: 32px;
                    background: transparent;
                    border: none;
                    outline: none;
                    text-indent: 12px;
                    font-size: .8rem;
                    // & 与input是同级样式
                    &::-webkit-input-placeholder {
                        font-size: .75rem;
                        color: @cdd;
                    }
                }
                .btn {
                    flex: 0 0 126px;
                    // flex设置以后，width是不生效的
                    // width: 150px;
                    border: solid 1px @primary;
                    font-size: .7rem;
                    line-height: 32px;
                    text-align: center;
                }
                > img{
                    width: 35px;
                    height: 35px;
                }
            }
            .van-checkbox {
                margin-bottom: 16px;
                font-size: .75rem;
            }
            .link {
                display: block;
                margin: 16px 0;
                line-height: 32px;
                font-size: .75rem;
                color: @primary;
            }
        }
    } 
</style>